package cn.matezk.lianlian.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.matezk.lianlian.dao.DeviceDao;
import cn.matezk.lianlian.model.Device;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.*;

@Component
@Slf4j
public class EzFlowTask {
    @Autowired
    private DeviceDao deviceDao;

    private static final String API_ID = "CDMTZKKJYXGS1184@2024";
    private static final String API_KEY = "437bebe90638a6a3";
    private static final String API_PWD = "fa6fb09698305e9c";

    @XxlJob("ezFlowSyncTask")
    public void execute() {
        Map<String, Object> form = new HashMap<>();
        form.put("id", API_ID);
        List<Device> cards = new ArrayList<>();
        int pageNo = 0;
        while (true) {
            String body = JSONUtil.createObj()
                    .set("pwd", API_PWD)
                    .set("method", "getSIMList")
                    .set("pageIndex", pageNo ++)
                    .set("cardType", "4G")
                    .toString();
            form.put("info", XorEncryptAndBaseNew(body, API_KEY));
            String response = HttpUtil.post("http://global.anhuiyk.cn:8006/m2m_api/v1/query/", form);
            JSONObject obj = JSONUtil.parseObj(response);
            if (!"0".equals(obj.getStr("resultCode")))  break;
            JSONObject description = obj.getJSONObject("description");
            if (ObjectUtil.isEmpty(description)) break;
            JSONArray array = description.getJSONArray("simList");
            if (ObjectUtil.isEmpty(array) || array.size() == 0)  break;
            for (int i = 0; i < array.size(); i ++) {
                JSONObject item = array.getJSONObject(i);
                Date expireDate = item.getDate("serviceEndTime");
                if (ObjectUtil.isNotNull(expireDate)) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(expireDate);
                    if (calendar.get(Calendar.DATE) == 1) {
                        calendar.add(Calendar.DATE, -1);
                    }
                    cards.add(Device.buildCard("EZ", item.getStr("iccid"), calendar.getTime()));
                } else {
                    cards.add(Device.buildCard("EZ", item.getStr("iccid"), null));
                }
            }
            if (array.size() == 0) break;
        }
        if (ObjectUtil.isNotEmpty(cards)) {
            List<List<Device>> array = CollUtil.split(cards, 500);
            for (List<Device> cs : array) {
                deviceDao.batchUpdateCardInfo(cs);
            }
        }
    }

    @XxlJob("erzCardStateTask")
    public void flowStop() {
        // 查询尔瞻卡已经到期的
        List<String> iccids = deviceDao.expireIccid("EZ");
        if (ObjectUtil.isEmpty(iccids)) return;
        for (String iccid : iccids) {
            try {
                String response = stateChange(iccid, 2);
                JSONObject obj = JSONUtil.parseObj(response);
                if (!"0".equals(obj.getStr("resultCode"))) continue;
                XxlJobHelper.log(String.format("修改卡号%s状态为停机", iccid));
                deviceDao.updateIccidState(iccid, 3);
            } catch (Exception e) {
                XxlJobHelper.log(e);
            }
        }
        // 查询已经续上费的
        iccids = deviceDao.renewedIccid("EZ");
        for (String iccid : iccids) {
            try {
                String response = stateChange(iccid, 0);
                JSONObject obj = JSONUtil.parseObj(response);
                if (!"0".equals(obj.getStr("resultCode"))) continue;
                deviceDao.updateIccidState(iccid, 1);
                XxlJobHelper.log(String.format("修改卡号%s状态为激活", iccid));
            } catch (Exception e) {
                XxlJobHelper.log(e);
            }
        }
    }

    private String stateChange(String iccid, Integer state) {
        Map<String, Object> form = new HashMap<>();
        form.put("id", API_ID);
        String body = JSONUtil.createObj()
                .set("pwd", API_PWD)
                .set("method", "disabledNumber")
                .set("iccid", iccid)
                .set("typeid", String.format("%d", state))
                .toString();
        form.put("info", XorEncryptAndBaseNew(body, API_KEY));
        return HttpUtil.post("http://global.anhuiyk.cn:8006/m2m_api/v1/query/", form);
    }

    public static String XorEncryptAndBaseNew(String str,String key) {
        byte[] b1 = str.getBytes();
        byte[] b2 = key.getBytes();
        byte[] out = new byte[b1.length];
        for (int i = 0; i < b1.length; i++) {
            out[i] = (byte) (b1[i] ^ b2[i % b2.length]);
        }
        return new URLEncoder().encode(Base64.getEncoder().encodeToString(out), Charset.defaultCharset());
    }
}
